package org.grow.secure.service;

import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.secure.entity.QPermission;
import org.grow.secure.entity.QPermissionRole;
import org.grow.secure.entity.QRoleInfo;
import org.grow.secure.entity.RoleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-7-20
 */

@Service
public class UrlDataSource implements FilterInvocationSecurityMetadataSource {

//    FilterInvocation ConfigAttribute
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//   第二步
//      不清楚o的类型可以打印  System.out.println(o.getClass());
        FilterInvocation fi = (FilterInvocation) o;
        HttpServletRequest httpRequest = fi.getHttpRequest();
        String method = httpRequest.getMethod().toUpperCase();
        String url = httpRequest.getRequestURI();

//        String url = "/leaveAbout/leave/submit/17";
        QPermission p = QPermission.permission;
        QPermissionRole pr = QPermissionRole.permissionRole;
        QRoleInfo r = QRoleInfo.roleInfo;
        List<RoleInfo> fetch = jpaQueryFactory.select(r)
                .from(p)
                .innerJoin(pr).on(p.permissionId.eq(pr.permissionFk))
                .innerJoin(r).on(pr.roleFk.eq(r.roleId))
                .where(p.httpMethod.eq(HttpMethod.resolve(method)))
                .where(Expressions.booleanTemplate("{0} like {1}", url, p.pathPattern))
                .fetch();
        List a = fetch;
        return a;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
